package org.example.controller;

import jakarta.annotation.Resource;
import org.example.entity.CommonResult;
import org.example.entity.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/UserController")
@RefreshScope
public class UserController {
    @Value("${msg}")
    private String msg;
    @Resource
    private UserService userService;

    @PostMapping("/addUser") //RO表示该接口 会返回一个对象
    public CommonResult<User> addUser(@RequestParam("id") String userId,
                          @RequestParam("pw") String password,
                         @RequestParam("name") String userName,
                         @RequestParam("sex") Integer userSex){
        User user = userService.addUser(userId,password,userName,userSex);//返回为空的话,就说明为0
        if(user != null){
            return new CommonResult<>(200, "success"+msg, user);
        }else{
            return new CommonResult<>(404, "注册失败，userId重复", null);
        }
    }

    @PostMapping("/findByUserIdAndPassword")
    public CommonResult<User> findByUserIdAndPassword(
            @RequestParam("id") String id,
            @RequestParam("pw") String pw) throws Exception{
        User user = userService.findByUserIdAndPassword(id,pw);
        if(user != null){
            return new CommonResult<>(200, "success", user);
        }else{
            return new CommonResult<>(404, "登录失败，用户名或密码错误", null);
        }
    }

    @GetMapping("/findByUserId/{userId}")
    public CommonResult<User> findByUserId(@PathVariable("userId") String userId) throws Exception{
        User user = userService.findUserById(userId);
        if(user != null){
            return new CommonResult<>(200, "success"+msg, user);
        }else{
            return new CommonResult<>(404, "找不到该用户", null);
        }
    }
}
